package Server;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.List;

import comunicationFrames.SearchRequest;
import comunicationFrames.SearchResponse;

public class SearchHandler implements Runnable {
	private Socket connection;
	private Database usersDb = new Database();
	private ObjectOutputStream socketWriter;
	private ObjectInputStream socketReader;
	private List<Socket> searchConnections;
	
	public SearchHandler(List<Socket> loginConnections) {
		super();
		this.searchConnections = loginConnections;
	}

	@Override
	public void run() {
		while (true) {
			synchronized (searchConnections) {
				while (searchConnections.isEmpty()) {
					try {
						searchConnections.wait();
					} catch (InterruptedException e) {
						return;
					}
				}
				connection = (Socket) searchConnections.remove(0);
			}
			handleConnection();
		}
	}
	
	private void handleConnection() {
		try {
			socketWriter = new ObjectOutputStream(
					connection.getOutputStream());
			socketReader = new ObjectInputStream(
					connection.getInputStream());
			SearchRequest request;
			SearchResponse response;
			Object o;
			o = socketReader.readObject();
			if (o instanceof SearchRequest) {
				request = (SearchRequest) o;
				List<String> searchResult;
				String name = request.getName();
				String surname = request.getSurname();
				String number = request.getNumber();
				searchResult = usersDb.searchContacts(name, surname, number);
				response = new SearchResponse(1, searchResult);
				socketWriter.writeObject(response);
			} else {
				response = new SearchResponse(-1, null);
				socketWriter.writeObject(response);
			}
			socketWriter.flush();
			closeConnection();
		} catch (FileNotFoundException e) {
			System.err.println(
					"Could not find requested file on the server.");
		} catch (IOException e) {
			System.err.println("Error handling a client: " + e);
		} catch (ClassNotFoundException e) {
			System.err.println("Error reading from socket: " + e);
		}
	}
	
	private void closeConnection() {
		try {
			if (socketWriter != null) {
				socketWriter.close();
			}
			if (socketReader != null) {
				socketReader.close();
			}
		} catch (IOException e) {
			System.err.println("Error closing a server: " + e);
		}
	}
}

